package com.ciwong.epaper.modules.me.ui;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.cordva.BaseHtmlActicity;
import com.ciwong.epaper.modules.cordva.SubmitEvent;
import com.ciwong.epaper.modules.me.bean.NewUserInfo;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.PayHelper;
import com.ciwong.eventbus.EventBus;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.GoBackListener;
import com.ciwong.mobilepay.bean.PayDetail;
import com.ciwong.mobilepay.ui.EMainActivity;

import org.json.JSONObject;

import java.io.File;

/**
 *参赛记录
 * Created by lzr on 2016/10/20.
 */
public class RegistRecodActivity extends BaseHtmlActicity  {

    public static final int REQUEST_PAY_CODE=100;
    //业务相关
    private int themeId;

    private boolean isSend=false;
    private int userId;
    private String no;


    @Override
    protected void init() {
        super.init();
        setGoBackListener(this);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void preCreate() {
        super.preCreate();
        themeId=getIntent().getIntExtra(IntentFlag.INTENT_FLAG_TYPE,1);
    }

    @Override
    protected void loadData() {
        super.loadData();
        setStartURL("file://" + ESystem.getRegistPath() + File.separator + "signUp.html?themeId="+themeId+"#!/record");
        cordovaWebView.loadUrl(startURL.toString());
    }


    @Override
    protected void onDestroy() {
        if(isSend){
            EventBus.getDefault().post(new SubmitEvent(null,"ref"));
        }
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
    /**
     * eventBus 回调方法
     * @param submitEvent
     */
    public void onEventMainThread(SubmitEvent submitEvent) {
        final  String id = submitEvent.getId();
        try {
            if ("SetTitle".equals(id)) {
                if (null != submitEvent.getJson()) {
                    JSONObject jsonObject = new JSONObject(submitEvent.getJson());
                    String title = jsonObject.getString("title");
                    setTitleText(title);
                }
            }else if("CallToPay".equals(id)){
                isSend=true;
                if (null != submitEvent.getJson()) {
                    Log.d(TAG,"----CallToPay-------"+submitEvent.getJson());
                    UserInfoBase userInfo = getUserInfoBase();
                    JSONObject  tempJson= new JSONObject(submitEvent.getJson());
                    JSONObject jsonObject=new JSONObject(tempJson.getString("data"));
                    //如果是金额等于0就报名成功
                    if(jsonObject.getDouble("fee")<=0){
                        showToastSuccess("报名成功");
                        loadData();
                    }else{
                        userId=(int)userInfo.getUserId();
                        no=jsonObject.getString("orderNo");
                        String Buymsg;
                        if(jsonObject.has("buyMsg")){
                            Buymsg=jsonObject.getString("buyMsg");
                        }else {
                            Buymsg=null;
                        }

                        PayDetail payDetail = PayHelper.getInstance().getPayDetail(userInfo.getUserId(), userInfo.getRealName(),jsonObject.getString("matchTitle"), "",
                                jsonObject.getDouble("fee"), jsonObject.getString("goodsName"), 1, 2,jsonObject.getString("notifyAddress") ,
                                jsonObject.getString("orderNo"),"", "9", "1", "999", "("+jsonObject.getString("stage")+")",
                                "比赛赛区："+jsonObject.getString("area")+"   比赛时长："+jsonObject.getString("duration")+"分钟","",Buymsg);
                        MeJumpManager.jumpToPay(R.string.go_back,payDetail,this,REQUEST_PAY_CODE);
                        loadData();
                    }
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {
        if (resultCode == RESULT_OK && data != null) {
            switch (requestCode) {
                case REQUEST_PAY_CODE:
                    int payResult = data.getIntExtra(EMainActivity.PAY_RESULT, 0);
                    // 支付购买成功
                    if (payResult == EMainActivity.PAY_RESULT_SUCCES) {
                        //当前页面也应该刷新下
                        showToastSuccess("报名成功");
//                        toRefPlayState();
                        loadData();
                    } else {
                        showToastError("报名失败");
                        loadData();
                    }
                    break;
                default:
                    break;
            }
        }
        hideMiddleProgressBar();
    }


    @Override
    public void goBack() {
        super.goBack();
        try {
            String endStr=cordovaWebView.getUrl().substring(cordovaWebView.getUrl().indexOf("?"),cordovaWebView.getUrl().length());
            if(endStr.equals("?themeId="+themeId+"#!/record")){
                finish();
            }else{
                cordovaWebView.backHistory();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
